"""
Copyright (c) 2025 Huawei Technologies Co., Ltd.
This file is a part of the CANN Open Software.
Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
Please refer to the License for details. You may not use this file except in compliance with the License.
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
See LICENSE in the root of the software repository for the full text of the License.
"""

import csv
import sys
import os
import ast
import numpy as np

def find_files_by_name(filename, root_dir='.'):
    file_paths = []
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file == filename:
                file_paths.append(os.path.join(root, file))
    return file_paths

def get_prof_from_all_kernel(prof_name, kernel_num, profiling_dict, path_dict, inner_kernel_mode, inter_kernel_mode, cube_or_vec): 
    """
    inner_kernel_mode: 0-avg; 1-max; 2-min; 3-sum
    inter_kernel_mode: 0-avg; 1-max; 2-min; 3-sum
    cube_or_vec: 0-none; 1-cube; 2-vector
    """
    prof = 0
    file_name = profiling_dict[prof_name]
    file_path_list = path_dict[file_name]
    for i in range(kernel_num):
        with open(file_path_list[i], newline='') as csvfile:

            reader = csv.DictReader(csvfile)
            
            cur_prof_list = []
            if cube_or_vec == 0:
                cur_prof_list = [float(row[prof_name]) for row in reader]
            elif cube_or_vec == 1:
                cur_prof_list = [float(row[prof_name]) for row in reader if row['sub_block_id'].startswith("cube")]
            elif cube_or_vec == 2:
                cur_prof_list = [float(row[prof_name]) for row in reader if row['sub_block_id'].startswith("vector")]

            cur_prof = 0
            if inner_kernel_mode == 0:
                cur_prof = sum(cur_prof_list[0:]) / len(cur_prof_list[0:])
            elif inner_kernel_mode == 1:
                cur_prof = max(cur_prof_list)
            elif inner_kernel_mode == 2:
                cur_prof = min(cur_prof_list)
            elif inner_kernel_mode == 3:
                cur_prof = sum(cur_prof_list)

            if inter_kernel_mode == 0: 
                prof = (prof * i + cur_prof) / (i+1)
            elif inter_kernel_mode == 1: 
                prof = max(prof, cur_prof)
            elif inter_kernel_mode == 2: 
                prof = min(prof, cur_prof)
            elif inter_kernel_mode == 3: 
                prof += cur_prof

    return np.round(prof, 6)



kernel_num = 1
size = len(sys.argv) - 1

zeroPaddingM = int(float(sys.argv[size - 5]))
zeroPaddingN = int(float(sys.argv[size - 4]))
zeroPaddingK = int(float(sys.argv[size - 3]))
batchCount = int(float(sys.argv[size - 2]))
A100_40G_cublas_time_us = float(sys.argv[size - 1])
ascblas_HgemmStrideBatched_time_us = float(sys.argv[size])

profiling_dict = {
    "Task Duration(us)":"OpBasicInfo.csv",
    "aic_total_hit_rate(%)":"L2Cache.csv", 
    "aic_cube_ratio":"PipeUtilization.csv", 
    "aic_mte2_ratio":"PipeUtilization.csv", 
    "aic_fixpipe_ratio":"PipeUtilization.csv"
}

path_dict = {
    "OpBasicInfo.csv":[], 
    "L2Cache.csv":[], 
    "PipeUtilization.csv":[]
}

for key in path_dict.keys():
    path_dict[key] = find_files_by_name(key)
    print(path_dict[key])

cann_var_sequence_gemm_time_us = get_prof_from_all_kernel("Task Duration(us)", kernel_num, profiling_dict, path_dict, 0, 0, 0)
cann_var_sequence_gemm_Tflops = np.round(2.0 * zeroPaddingM * zeroPaddingN * zeroPaddingK * batchCount * 1e-6 / cann_var_sequence_gemm_time_us, 6)
cann_var_sequence_gemm_speedup_rate = np.round(A100_40G_cublas_time_us / cann_var_sequence_gemm_time_us, 6)
cann_var_sequence_gemm_aic_total_hit_rate = get_prof_from_all_kernel("aic_total_hit_rate(%)", kernel_num, profiling_dict, path_dict, 0, 0, 1)
cann_var_sequence_gemm_aic_cube_ratio = get_prof_from_all_kernel("aic_cube_ratio", kernel_num, profiling_dict, path_dict, 0, 0, 1)
cann_var_sequence_gemm_aic_mte2_ratio = get_prof_from_all_kernel("aic_mte2_ratio", kernel_num, profiling_dict, path_dict, 0, 0, 1)
cann_var_sequence_gemm_aic_fixpipe_ratio = get_prof_from_all_kernel("aic_fixpipe_ratio", kernel_num, profiling_dict, path_dict, 0, 0, 1)

print("cann_var_sequence_gemm_time_us", " ", cann_var_sequence_gemm_time_us, 
    " ", "cann_var_sequence_gemm_Tflops", " ", cann_var_sequence_gemm_Tflops, 
    " ", "cann_var_sequence_gemm_speedup_rate", " ", cann_var_sequence_gemm_speedup_rate,  
    " ", "cann_var_sequence_gemm_aic_total_hit_rate", " ", cann_var_sequence_gemm_aic_total_hit_rate, 
    " ", "cann_var_sequence_gemm_aic_cube_ratio", " ", cann_var_sequence_gemm_aic_cube_ratio, 
    " ", "cann_var_sequence_gemm_aic_mte2_ratio", " ", cann_var_sequence_gemm_aic_mte2_ratio, 
    " ", "cann_var_sequence_gemm_aic_fixpipe_ratio", " ", cann_var_sequence_gemm_aic_fixpipe_ratio)
